package tut.fileLock;

import java.io.File;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.util.concurrent.locks.Lock;

public class FileLockTest {

	public static void main(String[] args) {
		RandomAccessFile file = null; // The file we'll lock
		FileChannel f = null; // The channel to the file
		FileLock lock = null; // The lock object we hold

		try { // The finally clause closes the channel and releases the lock
			// We use a temporary file as the lock file.
			String tmpdir = System.getProperty("java.io.tmpdir");
			String filename = Lock.class.getName() + ".lock";
			File lockfile = new File(tmpdir, filename);

			// Create a FileChannel that can read and write that file.
			// Note that we rely on the java.io package to open the file,
			// in read/write mode, and then just get a channel from it.
			// This will create the file if it doesn't exit. We'll arrange
			// for it to be deleted below, if we succeed in locking it.
			file = new RandomAccessFile(lockfile, "rw");
			f = file.getChannel();

			// Try to get an exclusive lock on the file.
			// This method will return a lock or null, but will not block.
			// See also FileChannel.lock() for a blocking variant.
			lock = f.tryLock();

			if (lock != null) {
				// We obtained the lock, so arrange to delete the file when
				// we're done, and then write the approximate time at which
				// we'll relinquish the lock into the file.
				lockfile.deleteOnExit(); // Just a temporary file

				// First, we need a buffer to hold the timestamp
				ByteBuffer bytes = ByteBuffer.allocate(8); // a long is 8 bytes

				// Put the time in the buffer and flip to prepare for writing
				// Note that many Buffer methods can be "chained" like this.
				bytes.putLong(System.currentTimeMillis() + 10000).flip();

				f.write(bytes); // Write the buffer contents to the channel
				f.force(false); // Force them out to the disk
			}
		} catch (Exception e) {
			System.out.println(e.toString());
		}
	}

}
